home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / screen-resolution-extra / screenresolution-mechanism.pyc (.txt) < prev   
Python Compiled Bytecode  |  2009-10-28  |  10KB  |  222 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import dbus
  5. import dbus.service as dbus
  6. import gobject
  7. import logging
  8. import os
  9. import os.path as os
  10. import sys
  11. from XKit import xutils, xorgparser
  12. import time
  13. import shutil
  14. import subprocess
  15.  
  16. try:
  17.     from dbus.lowlevel import HANDLER_RESULT_NOT_YET_HANDLED
  18. except ImportError:
  19.     from _dbus_bindings import HANDLER_RESULT_NOT_YET_HANDLED
  20.  
  21.  
  22. class AccessDeniedException(dbus.DBusException):
  23.     '''This exception is raised when some operation is not permitted.'''
  24.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.AccessDeniedException'
  25.  
  26.  
  27. class UnsupportedException(dbus.DBusException):
  28.     '''This exception is raised when some operation is not supported.'''
  29.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.UnsupportedException'
  30.  
  31.  
  32. class UsageError(dbus.DBusException):
  33.     '''This exception is raised when some operation was not used properly.'''
  34.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.UsageError'
  35.  
  36.  
  37. class PolicyKitService(dbus.service.Object):
  38.     '''A D-BUS service that uses PolicyKit for authorization.'''
  39.     
  40.     def _check_permission(self, sender, conn, action, reconnect = True):
  41.         '''
  42.         Verifies if the specified action is permitted, and raises
  43.         an AccessDeniedException if not.
  44.         '''
  45.         if sender is None and conn is None:
  46.             return None
  47.         dbus_info = dbus.Interface(conn.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus/Bus', False), 'org.freedesktop.DBus')
  48.         pid = dbus_info.GetConnectionUnixProcessID(sender)
  49.         polkit = dbus.Interface(get_service_bus().get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority', False), 'org.freedesktop.PolicyKit1.Authority')
  50.         
  51.         try:
  52.             (is_auth, _, details) = polkit.CheckAuthorization(('unix-process', {
  53.                 'pid': dbus.UInt32(pid, variant_level = 1) }), action, {
  54.                 '': '' }, dbus.UInt32(1), '', timeout = 600)
  55.         except dbus.DBusException:
  56.             conn is None
  57.             e = conn is None
  58.             if reconnect and e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
  59.                 return self._check_polkit_privilege(sender, conn, action, reconnect = False)
  60.             raise 
  61.         except:
  62.             e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown'
  63.  
  64.         if not is_auth:
  65.             logging.debug('_check_permission: sender %s on connection %s pid %i is not authorized for %s: %s' % (sender, conn, pid, action, str(details)))
  66.             raise AccessDeniedException(action)
  67.         is_auth
  68.  
  69.  
  70.  
  71. class BackendService(PolicyKitService):
  72.     '''A D-Bus service that PolicyKit controls access to.'''
  73.     INTERFACE_NAME = 'com.ubuntu.ScreenResolution.Mechanism'
  74.     SERVICE_NAME = 'com.ubuntu.ScreenResolution.Mechanism'
  75.     IDLE_TIMEOUT = 30
  76.     
  77.     def __init__(self, connection = None, path = '/'):
  78.         if connection is None:
  79.             connection = get_service_bus()
  80.         
  81.         super(BackendService, self).__init__(connection, path)
  82.         self._BackendService__name = dbus.service.BusName(self.SERVICE_NAME, connection)
  83.         self._BackendService__loop = gobject.MainLoop()
  84.         self._BackendService__timeout = 0
  85.         connection.add_message_filter(self._BackendService__message_filter)
  86.  
  87.     
  88.     def __message_filter(self, connection, message):
  89.         '''
  90.         D-BUS message filter that keeps the service alive,
  91.         as long as it receives message.
  92.         '''
  93.         if self._BackendService__timeout:
  94.             self._BackendService__start_idle_timeout()
  95.         
  96.         return HANDLER_RESULT_NOT_YET_HANDLED
  97.  
  98.     
  99.     def __start_idle_timeout(self):
  100.         '''Restarts the timeout for terminating the service when idle.'''
  101.         if self._BackendService__timeout:
  102.             gobject.source_remove(self._BackendService__timeout)
  103.         
  104.         self._BackendService__timeout = gobject.timeout_add(self.IDLE_TIMEOUT * 1000, self._BackendService__timeout_cb)
  105.  
  106.     
  107.     def __timeout_cb(self):
  108.         '''Timeout callback that terminates the service when idle.'''
  109.         if self.connection.list_exported_child_objects('/'):
  110.             return True
  111.         print 'Terminating %s due to inactivity.' % self.SERVICE_NAME
  112.         self._BackendService__loop.quit()
  113.         return False
  114.  
  115.     
  116.     def run(self):
  117.         '''Creates a GLib main loop for keeping the service alive.'''
  118.         print 'Running %s.' % self.SERVICE_NAME
  119.         print 'Terminating it after %d seconds of inactivity.' % self.IDLE_TIMEOUT
  120.         self._BackendService__start_idle_timeout()
  121.         self._BackendService__loop.run()
  122.  
  123.     
  124.     def setVirtual(self, virtres, sender = None, conn = None):
  125.         '''
  126.         Replace the first line of this example with a source and a destination file
  127.         '''
  128.         self._check_permission(sender, conn, 'com.ubuntu.screenresolution.mechanism.configure')
  129.         virtual = ' '.join(virtres)
  130.         source = '/etc/X11/xorg.conf'
  131.         destination = '/etc/X11/xorg.conf'
  132.         if os.path.exists(source):
  133.             backup = source + '.' + time.strftime('%Y%m%d%H%M%S')
  134.             shutil.copyfile(source, backup)
  135.         
  136.         
  137.         try:
  138.             a = xutils.XUtils(source)
  139.         except (IOError, xorgparser.ParseException):
  140.             a = xutils.XUtils()
  141.  
  142.         empty = True
  143.         for section in a.globaldict:
  144.             if len(a.globaldict[section]) > 0:
  145.                 empty = False
  146.                 break
  147.                 continue
  148.         
  149.         if empty:
  150.             a.makeSection('Device', 'Configured Video Device')
  151.             a.makeSection('Screen', identifier = 'Configured Screen Device')
  152.             a.addReference('Screen', 'Device', 'Configured Video Device', position = 0)
  153.             a.makeSubSection('Screen', 'Display', position = 0)
  154.             a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = 0)
  155.         else:
  156.             devicelen = len(a.globaldict['Device'])
  157.             screenlen = len(a.globaldict['Screen'])
  158.             if screenlen == 0:
  159.                 screen = a.makeSection('Screen', identifier = 'Configured Screen Device')
  160.                 if devicelen == 0:
  161.                     device = a.makeSection('Device', 'Configured Video Device')
  162.                 else:
  163.                     device = 0
  164.                 a.addReference('Screen', 'Device', 'Configured Video Device', position = device)
  165.                 a.makeSubSection('Screen', 'Display', position = 0)
  166.                 a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = 0)
  167.             else:
  168.                 for screen in a.globaldict['Screen']:
  169.                     a.makeSubSection('Screen', 'Display', position = screen)
  170.                     a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = screen)
  171.                 
  172.         a.writeFile(destination)
  173.         return True
  174.  
  175.     setVirtual = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 'as', out_signature = 'b', sender_keyword = 'sender', connection_keyword = 'conn')(setVirtual)
  176.     
  177.     def setDontZap(self, enable, sender = None, conn = None):
  178.         '''Try to set the DontZap option in the xorg.conf
  179.            and return the exit code of dontzap'''
  180.         self._check_permission(sender, conn, 'com.ubuntu.screenresolution.mechanism.dontzap')
  181.         dontzap_file = '/usr/bin/dontzap'
  182.         if not os.path.isfile(dontzap_file):
  183.             logging.error('/usr/bin/dontzap does not exist')
  184.             return 1
  185.         if enable in ('--enable', '--disable'):
  186.             logging.debug('calling dontzap with %s' % enable)
  187.             retcode = subprocess.call([
  188.                 dontzap_file,
  189.                 enable])
  190.             return retcode
  191.         logging.error('called with wrong arguments = %s' % enable)
  192.         return 1
  193.  
  194.     setDontZap = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 's', out_signature = 'i', sender_keyword = 'sender', connection_keyword = 'conn')(setDontZap)
  195.  
  196.  
  197. def get_service_bus():
  198.     '''Retrieves a reference to the D-BUS system bus.'''
  199.     return dbus.SystemBus()
  200.  
  201.  
  202. def get_service(bus = None):
  203.     '''Retrieves a reference to the D-BUS driven configuration service.'''
  204.     if not bus:
  205.         bus = get_service_bus()
  206.     
  207.     service = bus.get_object(BackendService.SERVICE_NAME, '/')
  208.     service = dbus.Interface(service, BackendService.INTERFACE_NAME)
  209.     return service
  210.  
  211. if __name__ == '__main__':
  212.     import sys
  213.     from sys import argv
  214.     from dbus.mainloop.glib import DBusGMainLoop
  215.     DBusGMainLoop(set_as_default = True)
  216.     if '--debug' in argv or '-d' in argv:
  217.         logging.basicConfig(stream = sys.stderr)
  218.         logging.getLogger().setLevel(logging.NOTSET)
  219.     
  220.     BackendService().run()
  221.  
  222.